package com.sbj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.SearchResult;
import cn.zhxu.bs.operator.Contain;

import cn.zhxu.bs.util.MapUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sbj.config.BuyOrderConfig;
import com.sbj.dto.req.BuyReq;
import com.sbj.dto.req.TransferGoodReq;
import com.sbj.dto.res.*;
import com.sbj.dto.utils.LocalDateTimeUtils;
import com.sbj.dto.utils.Search;
import com.sbj.entity.BuyGoods;
import com.sbj.entity.MemberStore;
import com.sbj.entity.OrderTime;
import com.sbj.mapper.BuyGoodsMapper;
import com.sbj.service.IBuyGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbj.service.IMemberService;
import com.sbj.service.IMemberStoreService;
import com.sbj.service.OrderTimeService;
import com.zmh.framework.constants.Constants;
import com.zmh.framework.exception.ResultException;
import com.zmh.framework.redis.RedisCache;
import com.zmh.framework.sys.dto.request.common.PageResponseDTO;
import lombok.AllArgsConstructor;
import org.redisson.api.RLock;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author summer
 * @since 2024/08/10 10:02:39
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class BuyGoodsServiceImpl extends ServiceImpl<BuyGoodsMapper, BuyGoods> implements IBuyGoodsService {

    private final BeanSearcher beanSearcher;

    @Override
    public Page<BuyRes> lists(BuyReq buyReq) {
        Map<String, Object> build = MapUtils.builder().page(buyReq.getPageNum() - 1, buyReq.getPageSize())
                .field(BuyRes::getGoodsName, buyReq.getGoodsName()).op(Contain.class).
          build();
        SearchResult<BuyRes> search = beanSearcher.search(BuyRes.class, build);
        return Search.searchDataList(buyReq.getPageNum(), buyReq.getPageSize(), search);
    }

    @Override
    public Page<BuyGoodsRes> webBuyGoods(PageResponseDTO pageResponseDTO) {
        Integer memberId =null;
        if(StpUtil.isLogin()){
            memberId = StpUtil.getLoginIdAsInt();
        }
        Map<String, Object> build = MapUtils.builder().page(pageResponseDTO.getPageNum() - 1, pageResponseDTO.getPageSize())
                .put("memberId",memberId)
                .field(BuyGoodsRes::getStatus,Constants.ZERO)
                .field(BuyGoodsRes::getDeleted,Constants.ZERO).build();
        return Search.searchDataList(pageResponseDTO.getPageNum(),pageResponseDTO.getPageSize(),beanSearcher.search(BuyGoodsRes.class,build));
    }


    private final BuyOrderConfig  orderConfig;



    @Override
    public void submitBuyOrder(BuyReq req) {
        orderConfig.submitBuyOrder(req);
    }

    @Override
    public MemberStoreRes payOrder(Integer id) {
        Map<String, Object> build = MapUtils.builder().field(MemberStoreRes::getId, id).build();
        return beanSearcher.searchFirst(MemberStoreRes.class,build);
    }



    @Override
    public void cancelBuyOrder(Integer storeId) {
        IMemberStoreService memberStoreService = SpringUtil.getBean(IMemberStoreService.class);
        MemberStore memberStore = memberStoreService.getById(storeId);
        if(ObjectUtil.isEmpty(memberStore)){
            throw new ResultException("支付订单不存在");
        }
        BuyGoods buyGoods = this.getById(memberStore.getBuyId());
        buyGoods.setStatus(Constants.ZERO);
        this.updateById(buyGoods);
        memberStore.setOrderState(Constants.TWO);
        memberStoreService.updateById(memberStore);
        //转拍订单记录修改
        if(buyGoods.getGrounding().equals(Constants.ONE)){
            MemberStore store = memberStoreService.getById(buyGoods.getBuyOrderId());
            store.setSellerId(null);
            store.setGradTime(null);
            memberStoreService.updateById(store);
        }

    }


    private final IMemberService memberService;



    @Override
    public CountDownRes countDown() {
        OrderTimeRes orderTimeRes = memberService.buyTime();
        CountDownRes countDownRes=new CountDownRes();
        if(LocalDateTimeUtil.isWeekend(LocalDate.now())){
            countDownRes.setStartTime(0L);
            countDownRes.setEndTime(0L);
            countDownRes.setIsTimeInRange(false);
            return countDownRes;
        }
        Long countDown = LocalDateTimeUtils.countDown(orderTimeRes.getStartTime(), orderTimeRes.getCountDown());
        countDownRes.setStartTime(countDown);
        if(countDown>0){
            countDownRes.setIsTime(true);
        }else{
            countDownRes.setIsTime(false);
        }
        countDownRes.setEndTime(LocalDateTimeUtils.between(orderTimeRes.getStartTime(), orderTimeRes.getEndTime()));
        countDownRes.setIsTimeInRange(LocalDateTimeUtils.isTimeInRange(orderTimeRes.getStartTime(),orderTimeRes.getEndTime(),LocalTime.now()));
        return countDownRes;
    }
}
